package apps.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import webframe.common.file.FileTransferHelper;
import webframe.common.file.MyUploadFileRenamePolicy;
import webframe.common.helper.FormatTransformHelper;
import apps.web.controller.base.MyBaseCommandController;
import apps.web.model.UploadFile;

public class ImgUploadController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request, HttpServletResponse response,
			Object command) {
		String tempId = FileTransferHelper.getParameter(request, "tempId");
		// 保存上传文件
		Map<File, MultipartFile> files = FileTransferHelper.storageUploadFile(request, "upload");
		Set<File> factFiles = files.keySet();
		List<UploadFile> fileRecords = new ArrayList<UploadFile>();
		if (factFiles.size() != 0) {
			for (File file : factFiles) {
				// 创建缩略图
				File previewImg = new File(FormatTransformHelper.getRealFilePathByKey("preview"),
						MyUploadFileRenamePolicy.getFileNameNotExtName(file) + ".jpg");
				FileTransferHelper.createPreviewImage(file, previewImg);

				// 数据库对象
				UploadFile uploadFile = new UploadFile();
				uploadFile.setTempId(tempId);
				uploadFile.setFileName(file.getName());
				uploadFile.setPreviewImgName(previewImg.getName());
				uploadFile.setContentType(files.get(file).getContentType());
				uploadFile.setRemark(FileTransferHelper.getParameter(request, files.get(file)
						.getName()
						+ "Remark"));
				fileRecords.add(uploadFile);
			}
		}

		// 删除文件
		String deletefiles = FileTransferHelper.getParameter(request, "deleteFiles");
		if (deletefiles != null && deletefiles.trim().length() != 0) {
			List<Long> deleteFileId = new ArrayList<Long>();
			String[] ids = deletefiles.split(";");
			for (int i = 0; i < ids.length; i++) {
				deleteFileId.add(Long.parseLong(ids[i]));
			}
			getServiceContainer().getFileBizService().deleteImgFiles(deleteFileId, "upload",
					"preview");
		}

		if (fileRecords.size() != 0) {
			getServiceContainer().getFileBizService().saveImgFiles(fileRecords);
		}
		return new ModelAndView(new RedirectView("ImgUpload.html?tempId="+tempId));
	}

}
